import Vue from "vue";
import Vuex from "vuex";
import $http from '@/utils/http';
import cart from './modules/cart';
import type from './modules/type';

// 导入持久化插件
import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex);
// 创建仓库
const store = new Vuex.Store({
  modules:{
    cart,
    type, 
  },


  plugins: [createPersistedState()],
  // 定义状态
  state: {
    token: "",
    phone: "123456789",
    username: "张三",
    age: 100,
  },

  getters: {
    // 派生状态
    str(state) {
      return `我叫${state.username},我的年龄是${state.age}`
    }
  },


  // 定义mutaion
  mutations: {
    // 修改token
    set_token(state,payload) {
      state.token = payload
    },

    // 修改phone的状态
    set_phone(state, payload) {
      state.phone = payload;
    },
    /**
     * 定义修改username的muation
     * @param {*} state 状态
     * @param {*} payload 传入的新数据
     */
    set_username(state, payload) {
      state.username = payload;
    },

    // 定义修改age的mutation
    set_age(state, payload) {
      state.age = payload;
    },
  },

  // 定义action
  actions: {
    LOGOUT(store,payload) {
      $http.post('/user/logout').then(res=> {
          // 清除token和phone
          store.commit('set_token','');
          store.commit('set_phone','');
      })
    }
  } 
});

export default store;
